import 'package:dio/dio.dart';

class ApiException implements Exception {
  final int code;
  final String message;
  
  ApiException(this.code, this.message);
  
  factory ApiException.fromDioError(DioException error) {
    switch (error.type) {
      case DioExceptionType.cancel:
        return ApiException(-1, '请求取消');
      case DioExceptionType.connectionTimeout:
        return ApiException(-1, '连接超时');
      case DioExceptionType.sendTimeout:
        return ApiException(-1, '请求超时');
      case DioExceptionType.receiveTimeout:
        return ApiException(-1, '响应超时');
      case DioExceptionType.badResponse:
        try {
          int? errCode = error.response?.statusCode;
          switch (errCode) {
            case 400:
              return ApiException(400, '请求语法错误');
            case 401:
              return ApiException(401, '未授权');
            case 403:
              return ApiException(403, '服务器拒绝执行');
            case 404:
              return ApiException(404, '无法连接服务器');
            case 405:
              return ApiException(405, '请求方法被禁止');
            case 500:
              return ApiException(500, '服务器内部错误');
            case 502:
              return ApiException(502, '网关错误');
            case 503:
              return ApiException(503, '服务不可用');
            case 505:
              return ApiException(505, 'HTTP版本不受支持');
            // 🔧 添加重定向状态码处理
            case 301:
            case 302:
            case 303:
            case 307:
            case 308:
              return ApiException(errCode!, '重定向处理失败，请检查请求URL');
            default:
              return ApiException(
                  errCode ?? -1, error.response?.statusMessage ?? '未知错误');
          }
        } on Exception catch (_) {
          return ApiException(-1, '未知错误');
        }
      case DioExceptionType.badCertificate:
        return ApiException(-1, '证书验证失败');
      case DioExceptionType.connectionError:
      case DioExceptionType.unknown:
        return ApiException(-1, error.message ?? '未知错误');
    }
  }
  
  @override
  String toString() {
    return 'ApiException{code: $code, message: $message}';
  }
} 